package com.sxm.yiwei.pinche;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.sxm.yiwei.R;
import com.sxm.yiwei.adapters.pinche.HostOrdersAdapter;
import com.sxm.yiwei.base.BaseActivity;
import com.sxm.yiwei.beans.pinche.HostOrder;
import com.sxm.yiwei.beans.pinche.Order;
import com.sxm.yiwei.beans.pinche.Route;
import com.sxm.yiwei.constant.Common;
import com.sxm.yiwei.constant.Constant;
import com.sxm.yiwei.utils.Calculator;
import com.sxm.yiwei.utils.DateUtil;
import com.sxm.yiwei.utils.HandleDataUtil;
import com.sxm.yiwei.views.AmountView;
import com.sxm.yiwei.views.MyListview;
import com.sxm.yiwei.views.PullToRefreshView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;


public class SelectChangeRouteActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private RelativeLayout rl_back;
    private TextView tv_title;
    private TextView tv_start_pos;
    private TextView tv_end_pos;
    private TextView tv_order_id;
    private MyListview listView;
    private TextView tv_selected_num;
    private Button btn_change_route;
    private ArrayList<HostOrder> hostLists=new ArrayList<>();
    private HostOrdersAdapter adapter;
    private int selectedTickets=0;
    private int httpAction=Constant.DEFAULT;
    private PullToRefreshScrollView refreshView;
    private ImageView noDataImg;
    private int page=1;
    private int pageSize=5;
    private ArrayList<Route> selectedRoutes=new ArrayList<>();
    private Order order;
    private int change_seats=0;
    private double total_amount=0.0;

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_select_change_route);
    }

    @Override
    public void initData() {
        order = (Order) getIntent().getSerializableExtra("order");
        tv_title.setText("选择改签路线");
        tv_start_pos.setText(order.getStart_place());
        tv_end_pos.setText(order.getEnd_place());
        tv_order_id.setText("订单号："+order.getOrder_code());
        adapter = new HostOrdersAdapter(this,hostLists,1);
        listView.setAdapter(adapter);

        adapter.setOnTicketChangeListener(new HostOrdersAdapter.OnTicketChangeListener() {
            @Override
            public void onTicketChange(int pre_amount, int amount, int position) {
                //showToast("选择座位数="+amount+" position="+position);
                HostOrder hostOrder = hostLists.get(position);
                if (hostOrder.isSelected()){
                    if (amount>pre_amount){
                        selectedTickets++;
                    }else if (amount<pre_amount){
                        selectedTickets--;
                    }
                }

                tv_selected_num.setText("已选票数"+selectedTickets+"张");
        }

            @Override
            public void onCheckedChange(boolean isChecked, int position) {
                HostOrder hostOrder = hostLists.get(position);
                if (hostOrder.isSelected()){
                    selectedTickets+=hostOrder.getTickets();
                }else {
                    selectedTickets-=hostOrder.getTickets();
                }
                tv_selected_num.setText("已选票数"+selectedTickets+"张");

            }
        });

        getRouteList();

    }


    @Override
    public void initView() {
        rl_back = (RelativeLayout)findViewById(R.id.rl_back);
        tv_title = (TextView)findViewById(R.id.tv_title);
        tv_start_pos = (TextView)findViewById(R.id.tv_start_pos);
        tv_end_pos = (TextView)findViewById(R.id.tv_end_pos);
        tv_order_id = (TextView)findViewById(R.id.tv_order_id);
        listView = (MyListview)findViewById(R.id.listView);
        tv_selected_num = (TextView)findViewById(R.id.tv_selected_num);
        btn_change_route = (Button)findViewById(R.id.btn_change_route);
        refreshView = (PullToRefreshScrollView)findViewById(R.id.refresh_view);
        refreshView.setMode(PullToRefreshBase.Mode.BOTH);
        ScrollView scrollView = refreshView.getRefreshableView();
        scrollView.smoothScrollTo(0,0);
        noDataImg = (ImageView)findViewById(R.id.iv_none_default);
    }

    @Override
    public void initListener() {
        rl_back.setOnClickListener(this);
        btn_change_route.setOnClickListener(this);
        listView.setOnItemClickListener(this);
        refreshView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(final PullToRefreshBase<ScrollView> refreshView) {
                httpAction=Constant.REFRESH;
                page=1;
                refreshView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getRouteList();
                        selectedTickets=0;
                        tv_selected_num.setText("已选票数"+selectedTickets+"张");
                        refreshView.onRefreshComplete();
                    }
                },2000);
            }

            @Override
            public void onPullUpToRefresh(final PullToRefreshBase<ScrollView> refreshView) {
                httpAction=Constant.LOAD_MORE;
                page++;
                refreshView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getRouteList();
                        refreshView.onRefreshComplete();
                    }
                },2000);
            }
        });
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()){
            case R.id.btn_change_route:
                /*for (int i = 0; i < hostLists.size(); i++) {
                    HostOrder hostOrder = hostLists.get(i);
                    if (hostOrder.isSelected()){
                        total_amount+=hostOrder.getTickets()*hostOrder.getSingle_money();
                    }
                }*/
                change_seats = Integer.parseInt(HandleDataUtil.withoutChinese(tv_selected_num.getText().toString().trim()));
                System.out.println("======="+HandleDataUtil.withoutChinese(tv_selected_num.getText().toString().trim()));
                if (change_seats==0){
                    showToast("请选择改签路线");
                    return;
                }
                if (change_seats>order.getSeats()){
                    showToast("改签座位数不能超过原订单总座位数！");
                    return;
                }
                changeFormOrder();

                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

    }
    /*
    * 获得改签列表
    * */
    private void getRouteList(){
        JSONObject object = new JSONObject();
        object.put("pinServiceKinds",order.getStyle()+"");
        object.put("pinStartPoint", order.getStart_place());
        object.put("pinEndPoint",order.getEnd_place());

        object.put("pageNo",page+"");
        object.put("pageSize",pageSize+"");
        httpGet(Common.HOST+Common.SEARCH_HOST_SURVICE,object,Constant.SEARCH_HOST_SURVICE);

        //模拟数据
        /*if (httpAction==Constant.DEFAULT||httpAction==Constant.REFRESH){
            hostLists.clear();
        }
        for (int i = 0; i < page*pageSize; i++) {
            HostOrder hostOrder = new HostOrder();
            if (i<2){
                hostOrder.setSeats(5);
            }else {
                hostOrder.setSeats(10);
            }
            if (httpAction==Constant.DEFAULT||httpAction==Constant.REFRESH){
                hostOrder.setSelected(false);
                hostOrder.setTickets(1);
            }
            hostOrder.setHttpAction(httpAction);
            hostLists.add(hostOrder);
        }
        if (hostLists.size()==0){
            noDataImg.setVisibility(View.VISIBLE);
        }
        adapter.notifyDataSetChanged();*/
    }
    private void changeFormOrder(){
        JSONObject object = new JSONObject();
        JSONArray array = new JSONArray();
        total_amount=0.0;
        for (int i = 0; i < hostLists.size(); i++) {
            HostOrder hostOrder = hostLists.get(i);
            if (hostOrder.isSelected()){
                total_amount+=hostOrder.getTickets()*hostOrder.getSingle_money();
                JSONObject obj = new JSONObject();
                obj.put("ownerId",hostOrder.getOwner_id());
                obj.put("serviceId",hostOrder.getService_id());
                obj.put("pinTotalAccount",hostOrder.getTickets()*hostOrder.getSingle_money()+"");
                obj.put("passerRequireSeats",hostOrder.getTickets()+"");
                obj.put("pinLoseAccount",hostOrder.getLoss_money()*hostOrder.getTickets()+"");
                Log.d("changeFormOrder"," pinTotalAccount="+hostOrder.getTickets()*hostOrder.getSingle_money()+" passerRequireSeats="+hostOrder.getTickets()+" pinLoseAccount="+hostOrder.getLoss_money());
                array.add(obj);
            }
        }
        object.put("serviceList",array.toString());
        object.put("orderId",order.getOrder_id());
        object.put("quit_amount",Calculator.getChangePayBack(change_seats*order.getSingle_money(),1)+"");//退还乘客的金额
        object.put("payment",Calculator.getChangePayBack(change_seats*order.getSingle_money(),0)+"");//赔付车主的金额
        object.put("alterTicketSeats",change_seats+"");//改签座位数
        object.put("after_total_amount",total_amount+"");//改签总票金额
        object.put("before_total_amount",change_seats*order.getSingle_money()+"");//改签前总票金额

        Log.d("changeFormOrder","quit_amount="+Calculator.getChangePayBack(total_amount,1)+""+" payment="+Calculator.getChangePayBack(total_amount,0)+""+" alterTicketSeats="+change_seats+" total_amount="+total_amount);

        httpPost(Common.HOST+Common.CHANGE_FORM_ORDER,object,Constant.CHANGE_FORM_ORDER);
    }
    @Override
    public void onSuccess(String result, String fromWhere) {
        super.onSuccess(result, fromWhere);
        com.alibaba.fastjson.JSONObject obj = JSON.parseObject(result);
        if (fromWhere==Constant.SEARCH_HOST_SURVICE){
            if (httpAction==Constant.DEFAULT||httpAction==Constant.REFRESH){
                hostLists.clear();
            }
            JSONArray data = obj.getJSONArray("data");
            for (int i = 0; i < data.size(); i++) {
                JSONObject jsonObject = data.getJSONObject(i);
                HostOrder hostOrder = new HostOrder();
                hostOrder.setStart_time(DateUtil.times(jsonObject.getLongValue("pinCreateTime")));
                hostOrder.setDepart_time(DateUtil.times(jsonObject.getLongValue("leaveOffTime")));
                hostOrder.setIcon(jsonObject.getString("ownerAvatar"));
                hostOrder.setSeats(jsonObject.getIntValue("ownerHasSeats"));
                hostOrder.setOwner_id(jsonObject.getString("ownerId"));
                hostOrder.setPhone(jsonObject.getString("ownerMobile"));
                hostOrder.setEnd_place(jsonObject.getString("pinEndPoint"));
                if (jsonObject.containsKey("pinLeaveWords")){
                    hostOrder.setWords(jsonObject.getString("pinLeaveWords"));
                }else {
                    hostOrder.setWords("");
                }
                hostOrder.setLoss_money(jsonObject.getDouble("pinLoseAccount"));
                hostOrder.setSingle_money(jsonObject.getDouble("pinServiceAccount"));
                hostOrder.setStyle(jsonObject.getIntValue("pinServiceKinds"));
                hostOrder.setStart_place(jsonObject.getString("pinStartPoint"));
                hostOrder.setDistance(jsonObject.getDouble("pinTotalDistance"));
                hostOrder.setService_id(jsonObject.getString("serviceId"));
                hostOrder.setVehicle_type(jsonObject.getIntValue("vehicleType"));
                hostOrder.setNickname(jsonObject.getString("ownerNickName"));
                hostOrder.setService_code(jsonObject.getString("pinServiceCode"));
                JSONArray imgs = jsonObject.getJSONArray("vehicleAvatarList");
                ArrayList<String> imgList = new ArrayList<>();
                for (int j = 0; j < imgs.size(); j++) {
                    String string = imgs.getString(j);
                    imgList.add(string);
                }
                hostOrder.setImgList(imgList);
                //hostOrder.setTotal_price(hostOrder.getSingle_money()*hostOrder.getSeats());
                hostOrder.setSelected(false);
                hostLists.add(hostOrder);
            }
            if (hostLists.size()==0){
                noDataImg.setVisibility(View.VISIBLE);
            }
            adapter.notifyDataSetChanged();

        }else if (fromWhere.equals(Constant.CHANGE_FORM_ORDER)){
            JSONObject data = obj.getJSONObject("data");
            double grapAmount=data.getDouble("grapAmount");
            String mixOrderId=data.getString("mixOrderId");
            JSONArray array = data.getJSONArray("serviceList");
            for (int i = 0; i < array.size(); i++) {
                JSONObject jsonObject = array.getJSONObject(i);
                Route route = new Route();
                route.setOrderId(jsonObject.getString("orderId"));
                route.setOwnerId(jsonObject.getString("ownerId"));
                route.setPasserRequireSeats(jsonObject.getString("passerRequireSeats"));
                route.setServiceId(jsonObject.getString("serviceId"));
                route.setTotalAmount(jsonObject.getString("totalAmount"));
                JSONObject carOwner = jsonObject.getJSONObject("carOwner");
                route.setOrderCode(carOwner.getString("orderCode"));
                route.setLeaveOffTime(carOwner.getLong("leaveOffTime"));
                route.setIcon(carOwner.getString("ownerAvatar"));
                route.setOwnerMobile(carOwner.getString("ownerMobile"));
                route.setOwnerNickName(carOwner.getString("ownerNickName"));
                route.setPinEndPoint(carOwner.getString("pinEndPoint"));
                route.setPinLeaveWords(carOwner.getString("pinLeaveWords"));
                route.setPinStartPoint(carOwner.getString("pinStartPoint"));
                route.setVehicleType(carOwner.getIntValue("vehicleType"));
                selectedRoutes.add(route);
            }
            showToast("生成订单成功");
            Intent intent = new Intent(this, PriceDifferenceActivity.class);
            intent.putParcelableArrayListExtra("selected_routes",selectedRoutes);
            intent.putExtra("grapAmount",grapAmount);
            intent.putExtra("mixOrderId",mixOrderId);
            startActivity(intent);
        }
    }

}
